import {
	companyParams
} from '@/utils/commen'

export function request(url, data = {}, method = 'GET', loadingDelay = 2000) {
	let token = wx.getStorageSync('token');
	!token && (token = '')
	let header = {}
	if (url != 'wx/auth/token') {
		header = {
			'X-Access-Token': token,
		}
	}

	var flag = false
	if (loadingDelay) {
		setTimeout(() => {
			if (!flag) {
				uni.showLoading({
					title: '数据请求中',
				})
			}
		}, loadingDelay)
	} else {
		uni.showLoading({
			title: '数据请求中',
		})
	}
	if (method == 'delete') {
		let query = ''
		for (var key in data) {
			query = key + '=' + data[key] + '&'
		}
		url = url + '?' + query
		data = {}
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: getApp().globalData.BASE_URL + url,
			method,
			data,
			header,
			success(res) {
				flag = true
				if (res.data.code == 401) {
					// uni.showToast({
					// 	duration: 3000,
					// 	title: '登录失效了，请重新登录',
					// 	icon: 'none'
					// })
					setTimeout(() => {
						uni.removeStorageSync('token')
						// 企业参数
						const {
							companyId,
							clientId,
							corpId
						} = companyParams()
						const urlArgs = [companyId ? `id=${companyId}` : '', clientId ?
							`clientId=${clientId}` : '', corpId ? `corpId=${corpId}` : ''
						]
						//如果是企业单
						if (window.location.href.indexOf('/pages/order') != -1) {
							uni.navigateTo({
								url: `/pages/companyMemberLogin`,
							})
						} else if (window.location.href.indexOf('/pages/company/allOrder') != -
							1) {
							//如果是企业单，且企业开启了实名登录，且token失效
							let companyInfo = uni.getStorageSync('companyInfo');
							let {
								realNameLogin
							} = companyInfo;
							if (realNameLogin == 1) {
								uni.redirectTo({
									url: `/pages/companyMemberLogin`,
								})
							}
						} else {
							//如果是个人单正常跳转
							uni.navigateTo({
								url: `/pages/login/login?${urlArgs.filter(_ => _).join('&')}`,
							})
						}
					}, 2000)
				}
				if (res.data.code == 500) {
					if (uni.getStorageSync('token') && res.data.message.indexOf('Token失效') != -1) {
						// uni.showToast({
						// 	duration: 3000,
						// 	icon: 'none',
						// 	title: '登录失效，正在重新登录...',
						// })
						setTimeout(() => {
							uni.removeStorageSync('token')
							uni.navigateTo({
								url: '/pages/login/login',
							})
						})
					}
				}
				uni.hideLoading()
				resolve(res)
			},
			fail(error) {
				flag = true
				console.log('error', error)
				uni.showToast({
					title: '请求失败',
					icon: 'error',
				})
				reject(error)
			},
		})
	})
}